package cn.qingfeng.a003_chat_v2_1.protocol;

import cn.qingfeng.a003_chat_v2_1.message.Message;
import com.google.gson.Gson;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.MessageToMessageCodec;

import java.nio.charset.StandardCharsets;
import java.util.List;

/**
 * 必须和 LengthFieldBasedFrameDecoder 一起使用，确保接到的 ByteBuf 消息是完整的
 */
@ChannelHandler.Sharable
public class MessageCodoc extends MessageToMessageCodec<ByteBuf, Message> {
    @Override
    protected void encode(ChannelHandlerContext ctx, Message out, List<Object> list) throws Exception {
        try {
            ByteBuf buffer = ctx.alloc().buffer();
            buffer.writeBytes(new Gson().toJson(out).getBytes(StandardCharsets.UTF_8));
            list.add(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void decode(ChannelHandlerContext ctx, ByteBuf in, List<Object> list) throws Exception {
        try {
            byte[] bytes = new byte[in.readableBytes()];
            in.readBytes(bytes);
            String inStr = new String(bytes, StandardCharsets.UTF_8);
            Message messageTemp = new Gson().fromJson(inStr, Message.class);
            String messageType = messageTemp.getMessageType();
            Class<? extends Message> msgClass = Message.messageClasses.get(messageType);

            Message message = new Gson().fromJson(inStr, msgClass);

            list.add(message);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
